/**
 * 
 */
package com.puneet.graphqueries.net;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author puneet
 * 
 */
public class TCPMessageReceiver implements Runnable {
	private int port;
	private BlockingQueue<String> messageQueue = (new LinkedBlockingQueue<String>());

	public TCPMessageReceiver(int port) {
		this.port = port;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public BlockingQueue<String> getMessageQueue() {
		return messageQueue;
	}

	public void run() {
		try {
			ServerSocket ss = new ServerSocket(port);
			while (true) {
				Socket socket = ss.accept();
				Thread t = new Thread(
						new TCPMessageReceiverThread(socket, this));
				t.start();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void messageReceived(String message) {

		if (message == null || "".equals(message)) {
			return;
		}
		synchronized (messageQueue) {
			System.out.println("Adding " + message);
			messageQueue.offer(message);
		}
	}

	public String takeFirstMessage() {
		try {
			return messageQueue.take();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public boolean hasMessages() {
		synchronized (messageQueue) {
			return this.messageQueue.size() > 0;
		}
	}
}
